package util

import (
	"bufio"
	"fmt"
	//"github.com/astaxie/beego/orm"
	"toxicity/models"
	//"io"
	"io/ioutil"
	"os"
	"os/exec"
	"sort"
	"strconv"
	"strings"
)

func callobabel(ifile, ofile string, parm string) bool {
	cmd := exec.Command("obabel", ifile, "-O", ofile, parm)
	buf, err := cmd.Output()
	if err != nil {
		fmt.Println("Fail to call obabel")
		fmt.Println(err)
		return false
	}
	fmt.Fprintf(os.Stdout, "%s", buf)
	return true
}

/*func GenInchiKey(folder string, molFileName string, mol string) string {
	inchiFile := folder + "/" + molFileName + ".inchikey"
	molFile := folder + "/" + molFileName + ".mol"
	os.MkdirAll(folder, os.ModeDir)
	fi, _ := os.Create(molFile)
	defer fi.Close()
	fi.WriteString(mol)

	cmd := exec.Command("obabel", molFile, "-O", inchiFile)
	buf, err := cmd.Output()
	if err != nil {
		return ""
	}
	fmt.Fprintf(os.Stdout, "%s", buf)
	inchiByte, _ := ioutil.ReadFile(inchiFile)
	inchikey := strings.TrimRight(string(inchiByte), "\n")
	inchikey = strings.TrimRight(inchikey, "\r")
	return inchikey
}
*/
/*
** return the 'txt' result file path of subSearch
** subSearchEXE : full path of executable file
** library :  the SD file of compound library
** query   : full path of the query mol file
** resFolder
 */
func SubSearch(subSearchEXE string, library string, query string, resFolder string) (string, error) {
	hitsTXT := resFolder + "/res.txt"
	//cmd4 := exec.Command("EXE/subsearch.exe", "query/allScaffolds.sdf", molFile, hitsTXT, maxhits)
	maxhits := "100"
	cmd4 := exec.Command(subSearchEXE, library, query, hitsTXT, maxhits)
	_, err := cmd4.Output()
	if err != nil {
		fmt.Println("Fail to call subsearch.exe")
		return "", err
	}
	//fmt.Fprintf(os.Stdout, "%s", buf3)
	return hitsTXT, nil
}

func ReadSubSearchRes(hitsTXT string) []string {
	file, err := os.Open(hitsTXT)
	if err != nil {
		panic(err)
		return nil
	}
	defer file.Close()
	var hits []string
	bytes, _ := ioutil.ReadAll(file)
	if len(bytes) == 0 {
		return hits
	}
	if bytes[len(bytes)-1] == ',' {
		bytes = bytes[0 : len(bytes)-1]
	}
	str := string(bytes)
	//fmt.Println(line)
	hits = strings.Split(strings.TrimSpace(str), ",")
	fmt.Println(hits)
	return hits
}
